package com.tf.mxj.controller;

import com.tf.mxj.dto.SignupRequest;
import com.tf.mxj.entity.ActivitySignup;
import com.tf.mxj.service.ActivitySignupService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/activity/signup")
public class ActivitySignupController {

    @Autowired
    private ActivitySignupService signupService;

    // 用户报名活动
    @PostMapping
    public String signup(@RequestBody @Valid SignupRequest request, BindingResult result) {
        if (result.hasErrors()) {
            return result.getFieldError().getDefaultMessage();
        }

        boolean exists = signupService.isUserSignedUp(request.getActivityId(), request.getUserId());
        if (exists) {
            return "你已报名该活动，不能重复报名。";
        }

        ActivitySignup signup = new ActivitySignup();
        signup.setActivityId(request.getActivityId());
        signup.setUserId(request.getUserId());

        boolean saved = signupService.save(signup);
        return saved ? "报名成功！" : "报名失败，请重试。";
    }

    // 查询用户是否已报名某活动
    @GetMapping("/check")
    public boolean checkSignup(@RequestParam Long activityId, @RequestParam Long userId) {
        return signupService.isUserSignedUp(activityId, userId);
    }

    // 取消报名
    @DeleteMapping
    public String cancelSignup(@RequestParam Long activityId, @RequestParam Long userId) {
        boolean removed = signupService.remove(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<ActivitySignup>()
                        .eq("activity_id", activityId)
                        .eq("user_id", userId));
        return removed ? "已取消报名" : "取消失败";
    }
}